﻿using UnityEngine;

namespace SnakeGame
{
    public class NodePoint
    {
        // 位置的二维索引
        public int x { get; set; }
        public int y { get; set; }

        // 点的预制体的引用
        public GameObject view { get; private set; }
        public RectTransform viewRect { get; set; }

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="res">点的资源</param>
        public NodePoint(GameObject res)
        {
            view = Object.Instantiate(res);
            view.transform.SetParent(GameObject.Find("UIViewGame/Bg/MapNode").transform);
            viewRect = view.GetComponent<RectTransform>();
        }

        /// <summary>
        /// 刷新点的位置
        /// </summary>
        /// <param name="a">在地图中横向的索引</param>
        /// <param name="b">在地图中纵向的索引</param>
        public void RefreshPosition(int a, int b)
        {
            x = a;
            y = b;
            var cor_x = (x - 0.5f) * Constant.Nwidth;
            var cor_y = -(y - 0.5f) * Constant.Nwidth;
            viewRect.anchoredPosition = new Vector2(cor_x, cor_y);
        }

        /// <summary>
        /// 增加位置增加量
        /// </summary>
        /// <param name="a">在地图中横向增量</param>
        /// <param name="b">在地图中纵向增量</param>
        public void AddPosition(int a, int b)
        {
            x += a;
            y += b;
            var cor_x = (x - 0.5f) * Constant.Nwidth;
            var cor_y = -(y - 0.5f) * Constant.Nwidth;
            viewRect.anchoredPosition = new Vector2(cor_x, cor_y);
        }

        /// <summary>
        /// 销毁时调用
        /// </summary>
        public void OnDestroy()
        {
            GameObject.DestroyImmediate(view);
        }
    }
}